const connection = require('./connect')
const sd = require('silly-datetime')

exports.Register = (formData, callback) => {
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss')
    connection.query(`select count(*) as count from users where username="${formData.username}";`, (err, data) => {
        if (err) return callback(err)
        else if (data[0].count == 0) {
            let addQuery = `insert into users values(null,"${formData.username}","${formData.password}","${formData.nick}","${time}","","2001-07-27",0,18);`
            connection.query(addQuery, (err, data) => {
                if (err) callback(err)
                return callback(null, { "code": 0, "message": "用户注册成功" })
            })
        } else if (data[0].count != 0) {
            return callback(null, { "code": 1, "message": "用户名重复" })
        }
    })
}


exports.Login = (formData, callback) => {
    connection.query(`select count(*) as count from users where username="${formData.username}";`, (err, data) => {
        if (err) return callback(err)
        else if (data[0].count == 1) {
            connection.query(`select username,password from users where username="${formData.username}";`, (err, data) => {
                if (err) callback(err)
                else if (data[0].username == formData.username && data[0].password == formData.password) {
                    return callback(null, { "code": 0, "message": "登录成功", })
                } else {
                    return callback(null, { "code": 1, "message": "用户名或密码错误", "data": formData.username })
                }
            })
        } else {
            return callback(null, { "code": 1, "message": "用户名或密码错误", })
        }
    })
}

exports.getUserInfo = (data, callback) => {
    connection.query(`select * from users where username="${data.username}";`, (err, data) => {
        if (err) return callback(err)
        return callback(null, {"code":0,"data":data[0],"message":"获取信息成功"});
    })
}

